package eip.chapter4.guaranteed;

import java.net.URISyntaxException;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.log4j.Logger;

import eip.chapter4.guaranteed.util.JiBXHelper;

public class FastDeliveryService implements MessageListener {
	
	private final static Logger logger = Logger.getLogger(FastDeliveryService.class);
	
	public FastDeliveryService() {
		try {
			ActiveMQConnection connection = ActiveMQConnection.makeConnection("tcp://localhost:61616");
		    connection.start();
		    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		    Destination destination = session.createQueue("groceryorder");
		    MessageConsumer consumer = session.createConsumer(destination);
		    consumer.setMessageListener(this);
		} catch(JMSException jms) {
			logger.error("error while connection to activemq", jms);
		} catch(URISyntaxException uri) {
			logger.error("error with activemq address", uri);
		}
	}
	
	public void onMessage(Message message) {
		processGroceryOrder(message);
	}
	
	public void processGroceryOrder(Message message) {
		try {
	        if(message == null || !(message instanceof TextMessage)) {
	        	logger.error("message is empty or is not a text message " + message);
	        	return;
	        }
	        TextMessage txtMessage = (TextMessage) message;
			GroceryOrder order = JiBXHelper.createOrderFromXML(txtMessage.getText());
			logger.info("received order: " + order);	
		} catch(Exception e) {
			logger.error("error while creating grocery order from text string", e);
		} 
	}
	
}
